﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameSave.Common.Misc
{
    public class ConfigHelper
    {
        public static List<T> GetConfigList<T>(string dirPath)
        {
            List<T> results = new List<T>();
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            DirectoryInfo di = new DirectoryInfo(dirPath);
            FileInfo[] fiList = di.GetFiles("*.*");
            foreach (FileInfo fi in fiList)
            {
                string jsonContent = File.ReadAllText(fi.FullName);
                List<T> configs = JsonConvert.DeserializeObject<List<T>>(jsonContent);
                results.AddRange(configs);
            }
            return results;


            //else
            //{
            //    throw new DirectoryNotFoundException($"Get Config Error\nDirectory '{dirPath}' Not Existed!");
            //}
        }

        public static bool SetConfig<T>(T cfgEntity, string fileFullName)
        {
            string jsonContent = JsonConvert.SerializeObject(cfgEntity);
            File.WriteAllText(fileFullName, jsonContent);
            return true;
        }

        public static T GetConfig<T>(string fileFullName)
        {
            string jsonContent = File.ReadAllText(fileFullName);
            return JsonConvert.DeserializeObject<T>(jsonContent);
        }
    }
}
